package com.dy.yunying.biz.service.prize.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.prize.PrizeConfig;
import com.dy.yunying.api.entity.prize.PrizeGiftBag;
import com.dy.yunying.api.enums.PrizeTypeEnum;
import com.dy.yunying.api.utils.FileUtils;
import com.dy.yunying.biz.dao.ads.prize.PrizeGiftBagMapper;
import com.dy.yunying.biz.service.prize.PrizeGiftBagService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 奖品礼包码
 *
 * @author chenxiang
 * @version 2022-04-25 16:25:54 table: prize_gift_bag
 */
@Log4j2
@Service("prizeGiftBagService")
@RequiredArgsConstructor
public class PrizeGiftBagServiceImpl extends ServiceImpl<PrizeGiftBagMapper, PrizeGiftBag>
		implements PrizeGiftBagService {

	private static final Pattern GIFT_CODE_PATTERN = Pattern.compile("^[A-Za-z0-9]{3,50}$");

	@Override
	public R saveUniqueGiftBag(MultipartFile file, Integer prizeType, Long sourceId) {
		List<String> readList = FileUtils.readFileContent(file);
		if (CollectionUtils.isEmpty(readList)) {
			throw new RuntimeException("读取礼包码信息失败");
		}
		List<String> list = readList.stream().distinct().collect(Collectors.toList());
		list = list.stream().filter(item -> item.trim().length() >= 3 && item.trim().length() <= 50)
				.collect(Collectors.toList());
		List<PrizeGiftBag> saveList = new ArrayList<PrizeGiftBag>();
		List<String> gitCodeList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(list)) {
			QueryWrapper<PrizeGiftBag> wrapper = new QueryWrapper<>();
			wrapper.in("gift_code", list);
			wrapper.eq("deleted", 0);
			List<PrizeGiftBag> resultList = this.list(wrapper);
			PrizeGiftBag giftBag;
			for (String str : list) {
				if (StringUtils.isNotBlank(str) && str.length() > 0) {
					String code = str.trim();
					if (CollectionUtils.isNotEmpty(resultList)) {
						int num = resultList.stream().filter(item -> code.equals(item.getGiftCode()))
								.collect(Collectors.toList()).size();
						if (num > 0) {
							continue;
						}
					}
					if (!GIFT_CODE_PATTERN.matcher(code).find()) {
						continue;
					}
					giftBag = new PrizeGiftBag();
					PrizeTypeEnum prizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeType);
					if (prizeTypeEnum == PrizeTypeEnum.BAGCODE){
						giftBag.setSourceType(1);
					} else {
						giftBag.setSourceType(2);
					}
					giftBag.setSourceId(sourceId);
					giftBag.setGiftCode(code);
					giftBag.setGiftAmount(1L);
					giftBag.setCreateTime(new Date());
					giftBag.setUpdateTime(new Date());
					giftBag.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
					giftBag.setUpdateId(SecurityUtils.getUser().getId().longValue());
					gitCodeList.add(code);
					saveList.add(giftBag);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(saveList)) {
			this.saveBatch(saveList);
		}
		int giftBagSize = saveList.size();
		return R.ok(gitCodeList, " 礼包码、卡密上传成功：" + giftBagSize + "个，重复无效过滤：" + (readList.size() - giftBagSize) + "个");
	}

	@Override
	public R saveCommonGiftBag(PrizeConfig prizeConfig) {
		PrizeTypeEnum prizeTypeEnum = PrizeTypeEnum.getPrizeTypeEnum(prizeConfig.getPrizeType());
		Integer sourceType;
		if (prizeTypeEnum == PrizeTypeEnum.BAGCODE){
			sourceType = 1;
		}else {
			sourceType = 2;
		}
		PrizeGiftBag prizeGiftBag = this
				.getOne(Wrappers.<PrizeGiftBag>lambdaQuery().eq(PrizeGiftBag::getSourceType, sourceType)
						.eq(PrizeGiftBag::getSourceId, prizeConfig.getId()).last("LIMIT 1"));
		if (Objects.isNull(prizeGiftBag)) {
			PrizeGiftBag giftBag = new PrizeGiftBag();
			giftBag.setSourceType(sourceType);
			giftBag.setSourceId(prizeConfig.getId());
			giftBag.setGiftCode(prizeConfig.getGiftCode());
			giftBag.setGiftAmount(Long.valueOf(prizeConfig.getGiftAmount()));
			giftBag.setUsable(prizeConfig.getGiftType());
			giftBag.setCreateTime(new Date());
			giftBag.setUpdateTime(new Date());
			giftBag.setCreateId(Long.valueOf(SecurityUtils.getUser().getId()));
			this.save(giftBag);
		} else {
			PrizeGiftBag updateGift = new PrizeGiftBag();
			updateGift.setId(prizeGiftBag.getId());
			updateGift.setGiftCode(prizeConfig.getGiftCode());
			updateGift.setGiftAmount(Long.valueOf(prizeConfig.getGiftAmount()));
			updateGift.setDeleted(0);
			this.updateById(updateGift);
		}
		return R.ok(prizeConfig);
	}

}
